﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lucene.Net.Documents;
using Lucene.Net.Search;
using Lucene.Net.Analysis;
using Vit.Data;
using Vit.PlugIn.Lucene.Converters;

namespace Vit.PlugIn.Lucene.Converters
{
    public class EntityDocumentConverter : IDataConverter
    {
        public EntityDocumentConverter()
        {
        }

        #region IDataConverter Members

        /// <summary>
        /// convert entity to lucene document
        /// </summary>
        /// <param name="obj">entity object</param>
        /// <param name="targetType">Lucene Document</param>
        /// <param name="parameter">converting parameter</param>
        /// <returns>Lucene Document</returns>
        public object Convert(object obj, Type targetType, object parameter)
        {
            DocumentInfo docInfo = parameter as DocumentInfo;
            if (obj == null || docInfo == null)
                return null;

            Document document = new Document();
            docInfo.EntityAccessor.Entity = obj;
            foreach (FieldInfo fi in docInfo.Fields)
            {
                Field field = new Field(fi.FieldName, docInfo.EntityAccessor.GetField(fi.PropertyName), InternalLuceneConverter.ConvertToFieldStore(fi.Store), InternalLuceneConverter.ConvertToFieldIndex(fi.Index));
                if(fi.Boost != 1.0f)
                    field.SetBoost(fi.Boost);
                document.Add(field);
            }
            return document;
        }

        /// <summary>
        /// convert lucene document back to entity object
        /// </summary>
        /// <param name="obj">Lucene Document</param>
        /// <param name="targetType">Lucene Document</param>
        /// <param name="parameter">converting parameter</param>
        /// <returns>entity object</returns>
        public object ConvertBack(object obj, Type targetType, object parameter)
        {
            Document document = obj as Document;
            DocumentInfo docInfo = parameter as DocumentInfo;
            if (document == null || docInfo == null)
                return null;

            docInfo.EntityAccessor.CreateNewEntity();
            foreach (FieldInfo fi in docInfo.Fields)
            {
                string value = document.GetField(fi.FieldName).StringValue();
                docInfo.EntityAccessor.SetField(fi.PropertyName, value);
            }

            return docInfo.EntityAccessor.Entity;
        }

        #endregion
    }
}
